package com.linkage.educloud.ah.widget;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.adapter.face.FaceListAdapter;
import com.linkage.educloud.ah.util.FaceUtils;
import com.linkage.educloud.ah.view.activity.classspace.DynamicWriterTextActivity;
import com.linkage.educloud.ah.view.activity.topic.TopicWriterActivity;

import java.util.ArrayList;
import java.util.List;

import static com.linkage.educloud.ah.util.FaceUtils.FACES;
import static com.linkage.educloud.ah.util.FaceUtils.FACES_JSJ;

/**
 * 自定义客户端表情栏  封装所有表情栏的操作
 * 用法：  传参见installView的注释
 * 1---使用自义定输入框时，只需实现installView  以及send点击事件的接口
 * 2---不使用自定义输入框时，需实现installView，在原界面仅需实现他的显示隐藏，以及提供一个方法（点击editext时改变表情图标的状态）
 * Created by Mr'Tang on 2018/9/25.
 */

public class PanelView extends LinearLayout {

    Context mContext;
    EditText view_panel_edit;
    ImageView view_panel_face;
    ImageView view_panel_send;
    GridView view_panel_grid;
    LinearLayout view_panel_bottom;
    ImageView view_panel_system;
    ImageView view_panel_jsj;
    View view_panel_line;
    LinearLayout view_panel_ed;

    private List<FaceUtils.Face> list = new ArrayList<>();
    private int face_type = 1;//1--系统表情 2--教师节表情
    private int is_show_face = 0;//0--隐藏  1--显示
    private FaceListAdapter adapter;

    private OnSendClickListener onSendClickListener;

    String before = "";//改变前输入框内容
    String after = "";//改变后输入框内容
    int index = 0;//输入框光标值

    EditText ed;

    /**
     * @param context
     * @param attrs
     */
    public PanelView(final Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.view_face_panelview, this, true);
        view_panel_ed = findViewById(R.id.view_panel_ed);
        view_panel_edit = findViewById(R.id.view_panel_edit);
        view_panel_face = findViewById(R.id.view_panel_face);
        view_panel_send = findViewById(R.id.view_panel_send);
        view_panel_grid = findViewById(R.id.view_panel_grid);
        view_panel_bottom = findViewById(R.id.view_panel_bottom);
        view_panel_system = findViewById(R.id.view_panel_system);
        view_panel_jsj = findViewById(R.id.view_panel_jsj);
        view_panel_line = findViewById(R.id.view_panel_line);
        this.mContext = context;
    }

    /**
     * 初始化各种事件
     *
     * @param face_num 底部表情的种类 1--只有系统表情 2--包含教师节表情
     * @param is_use   是否使用自定义输入框 1--使用 2--不使用
     * @param editText 不使用自定义输入框时传入原界面的输入框
     */
    public void installView(final int face_num, int is_use, EditText editText) {
        if (is_use == 1) {
            ed = view_panel_edit;
            //点击小表情，0--出来表情grid，隐藏系统软键盘 1--隐藏表情grid，展示软键盘
            view_panel_face.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (is_show_face == 0) {
                        view_panel_face.setImageResource(R.mipmap.ic_btn_face_on);
                        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0);
                        //延时0.3秒 以解决表情栏展示比隐藏输入法快,界面被顶上去的bug（目前没想到其他好方法）
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                view_panel_grid.setVisibility(VISIBLE);
                                view_panel_bottom.setVisibility(VISIBLE);
                                //根据参数判断显示表情的种类
                                if (face_num == 1) {
                                    view_panel_system.setVisibility(VISIBLE);
                                    view_panel_jsj.setVisibility(GONE);
                                    view_panel_line.setVisibility(GONE);
                                } else if (face_num == 2) {
                                    view_panel_system.setVisibility(VISIBLE);
                                    view_panel_jsj.setVisibility(VISIBLE);
                                    view_panel_line.setVisibility(VISIBLE);
                                }
                                list = FACES;
                                adapter = new FaceListAdapter(mContext, list);
                                view_panel_grid.setAdapter(adapter);

                                is_show_face = 1;
                            }
                        }, 300);
                    } else if (is_show_face == 1) {
                        view_panel_face.setImageResource(R.mipmap.ic_btn_face_off);
                        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(ed, InputMethodManager.SHOW_FORCED);


                        view_panel_grid.setVisibility(GONE);
                        view_panel_bottom.setVisibility(GONE);
                        ed.setFocusable(true);

                        is_show_face = 0;
                    }
                }
            });

            //点击edittext时隐藏表情栏
            ed.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    index = ed.getSelectionStart();
                    view_panel_grid.setVisibility(GONE);
                    view_panel_bottom.setVisibility(GONE);
                    view_panel_face.setImageResource(R.mipmap.ic_btn_face_off);
                    is_show_face = 0;
                }
            });

            //给发送按钮设置点击事件
            view_panel_send.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    onSendClickListener.onSendClick(ed.getText().toString());
                }
            });
        } else if (is_use == 2) {
            ed = editText;

            view_panel_ed.setVisibility(GONE);
            view_panel_grid.setVisibility(VISIBLE);
            view_panel_bottom.setVisibility(VISIBLE);
            //根据参数判断显示表情的种类
            if (face_num == 1) {
                view_panel_system.setVisibility(VISIBLE);
                view_panel_jsj.setVisibility(GONE);
                view_panel_line.setVisibility(GONE);
            } else if (face_num == 2) {
                view_panel_system.setVisibility(VISIBLE);
                view_panel_jsj.setVisibility(VISIBLE);
                view_panel_line.setVisibility(VISIBLE);
            }
            list = FACES;
            adapter = new FaceListAdapter(mContext, list);
            view_panel_grid.setAdapter(adapter);

            //点击edittext时隐藏表情栏
            ed.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    index = ed.getSelectionStart();
                    if (mContext instanceof DynamicWriterTextActivity) {
                        ((DynamicWriterTextActivity) mContext).change();
                    } else if (mContext instanceof TopicWriterActivity) {
                        ((TopicWriterActivity) mContext).change();
                    }
                }
            });
        }

        //监听edittext 已解决在表情前和中间无法输入文字的bug
        ed.addTextChangedListener(new JT());

        //展示系统表情
        view_panel_system.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (face_type == 1) {
                    return;
                }
                view_panel_jsj.setBackgroundColor(getResources().getColor(R.color.transparent));
                view_panel_system.setBackgroundColor(getResources().getColor(R.color.light_gray));
                face_type = 1;

                list = FACES;
                adapter = new FaceListAdapter(mContext, list);
                view_panel_grid.setAdapter(adapter);
            }
        });

        //展示教师节表情
        view_panel_jsj.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (face_type == 2) {
                    return;
                }
                view_panel_jsj.setBackgroundColor(getResources().getColor(R.color.light_gray));
                view_panel_system.setBackgroundColor(getResources().getColor(R.color.transparent));
                face_type = 2;

                list = FACES_JSJ;
                adapter = new FaceListAdapter(mContext, list);
                view_panel_grid.setAdapter(adapter);
            }
        });

        //给表情设置点击事件
        view_panel_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Editable editable = ed.getText();
                editable.insert(ed.getSelectionStart(), ExpressionUtils.replaceFace(mContext, list.get(position).text));
            }
        });
    }

    //发送点击事件接口
    public interface OnSendClickListener {
        void onSendClick(String text);
    }

    //外露发送点击事件方法 返回输入框的内容
    public void setOnSendClickListener(@Nullable OnSendClickListener listener) {
        onSendClickListener = listener;
    }

    class JT implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            before = ed.getText().toString();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            //先移除监听，再设置文本，否则会无限死循环
            after = ed.getText().toString();
            ed.removeTextChangedListener(this);
            //假如前后不一致就settext
            if (!after.equals(before)) {
                ed.setText(ExpressionUtils.replaceFace(mContext, after));
                //将点击位置的光标加上 前后长度差 即为现在的光标点
                ed.setSelection(index + (after.length() - before.length()));
                //将光标重新赋值
                index = index + (after.length() - before.length());
            }
            //settext后继续添加监听
            ed.addTextChangedListener(JT.this);
        }
    }

    public void clearED() {
        ed.setText("");
        ed.setFocusable(true);
        ed.requestFocus();
        ed.setSelection(ed.getText().toString().length());

        view_panel_face.setImageResource(R.mipmap.ic_btn_face_off);
        view_panel_grid.setVisibility(GONE);
        view_panel_bottom.setVisibility(GONE);
        is_show_face = 0;
        //隐藏输入法
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0);
    }

    public void andFocusable() {
        //给输入框设置焦点
        ed.setFocusable(true);
        ed.requestFocus();
        ed.setSelection(ed.getText().toString().length());
        //唤起输入法
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }
}